<!DOCTYPE html>
<html lang="en-us">
  <head>

    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    
<meta charset="UTF-8">
<title>什么是相关性? | Elasticsearch: 权威指南 | Elastic</title>
<link rel="home" href="index.html" title="Elasticsearch: 权威指南">
<link rel="up" href="sorting.html" title="排序与相关性">
<link rel="prev" href="multi-fields.html" title="字符串排序与多字段">
<link rel="next" href="docvalues-intro.html" title="Doc Values 介绍">
<meta name="DC.type" content="Learn/Docs/Elasticsearch/Definitive Guide">
<meta name="DC.subject" content="Elasticsearch">
<meta name="DC.identifier" content="2.x">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdn.optimizely.com/js/18132920325.js"></script>
    <link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png">
    <link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
    <link rel="icon" type="image/png" href="/android-chrome-192x192.png" sizes="192x192">
    <link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96">
    <link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
    <link rel="manifest" href="/manifest.json">
    <meta name="apple-mobile-web-app-title" content="Elastic">
    <meta name="application-name" content="Elastic">
    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="/mstile-144x144.png">
    <meta name="theme-color" content="#ffffff">
    <meta name="naver-site-verification" content="936882c1853b701b3cef3721758d80535413dbfd">
    <meta name="yandex-verification" content="d8a47e95d0972434">
    <meta name="localized" content="true">
    <meta name="st:robots" content="follow,index">
    <meta property="og:image" content="https://www.elastic.co/static/images/elastic-logo-200.png">
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
    <link rel="icon" href="/favicon.ico" type="image/x-icon">
    <link rel="apple-touch-icon-precomposed" sizes="64x64" href="/favicon_64x64_16bit.png">
    <link rel="apple-touch-icon-precomposed" sizes="32x32" href="/favicon_32x32.png">
    <link rel="apple-touch-icon-precomposed" sizes="16x16" href="/favicon_16x16.png">
    <!-- Give IE8 a fighting chance -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <link rel="stylesheet" type="text/css" href="/guide/static/styles.css">
  </head>

  <!--© 2015-2021 Elasticsearch B.V. Copying, publishing and/or distributing without written permission is strictly prohibited.-->

  <body>
    <!-- Google Tag Manager -->
    <script>dataLayer = [];</script><noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-58RLH5" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
    <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= '//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-58RLH5');</script>
    <!-- End Google Tag Manager -->

    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-12395217-16"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
      gtag('config', 'UA-12395217-16');
    </script>

    <!--BEGIN QUALTRICS WEBSITE FEEDBACK SNIPPET-->
    <script type="text/javascript">
      (function(){var g=function(e,h,f,g){
      this.get=function(a){for(var a=a+"=",c=document.cookie.split(";"),b=0,e=c.length;b<e;b++){for(var d=c[b];" "==d.charAt(0);)d=d.substring(1,d.length);if(0==d.indexOf(a))return d.substring(a.length,d.length)}return null};
      this.set=function(a,c){var b="",b=new Date;b.setTime(b.getTime()+6048E5);b="; expires="+b.toGMTString();document.cookie=a+"="+c+b+"; path=/; "};
      this.check=function(){var a=this.get(f);if(a)a=a.split(":");else if(100!=e)"v"==h&&(e=Math.random()>=e/100?0:100),a=[h,e,0],this.set(f,a.join(":"));else return!0;var c=a[1];if(100==c)return!0;switch(a[0]){case "v":return!1;case "r":return c=a[2]%Math.floor(100/c),a[2]++,this.set(f,a.join(":")),!c}return!0};
      this.go=function(){if(this.check()){var a=document.createElement("script");a.type="text/javascript";a.src=g;document.body&&document.body.appendChild(a)}};
      this.start=function(){var a=this;window.addEventListener?window.addEventListener("load",function(){a.go()},!1):window.attachEvent&&window.attachEvent("onload",function(){a.go()})}};
      try{(new g(100,"r","QSI_S_ZN_emkP0oSe9Qrn7kF","https://znemkp0ose9qrn7kf-elastic.siteintercept.qualtrics.com/WRSiteInterceptEngine/?Q_ZID=ZN_emkP0oSe9Qrn7kF")).start()}catch(i){}})();
    </script><div id="ZN_emkP0oSe9Qrn7kF"><!--DO NOT REMOVE-CONTENTS PLACED HERE--></div>
    <!--END WEBSITE FEEDBACK SNIPPET-->

    <div id="elastic-nav" style="display:none;"></div>
    <script src="https://www.elastic.co/elastic-nav.js"></script>

    <!-- Subnav -->
    <div>
      <div>
        <div class="tertiary-nav d-none d-md-block">
          <div class="container">
            <div class="p-t-b-15 d-flex justify-content-between nav-container">
              <div class="breadcrum-wrapper"><span><a href="/guide/" style="font-size: 14px; font-weight: 600; color: #000;">Docs</a></span></div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="main-container">
      <section id="content">
        <div class="content-wrapper">

          <section id="guide" lang="zh_cn">
            <div class="container">
              <div class="row">
                <div class="col-xs-12 col-sm-8 col-md-8 guide-section">
                  <!-- start body -->
                  <div class="page_header">
<b>请注意:</b><br>本书基于 Elasticsearch 2.x 版本，有些内容可能已经过时。
</div>
<div id="content">
<div class="breadcrumbs">
<span class="breadcrumb-link"><a href="index.html">Elasticsearch: 权威指南</a></span>
»
<span class="breadcrumb-link"><a href="getting-started.html">基础入门</a></span>
»
<span class="breadcrumb-link"><a href="sorting.html">排序与相关性</a></span>
»
<span class="breadcrumb-node">什么是相关性?</span>
</div>
<div class="navheader">
<span class="prev">
<a href="multi-fields.html">« 字符串排序与多字段</a>
</span>
<span class="next">
<a href="docvalues-intro.html">Doc Values 介绍 »</a>
</span>
</div>
<div class="section">
<div class="titlepage"><div><div>
<h2 class="title">
<a id="relevance-intro"></a>什么是相关性?<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elasticsearch-cn/elasticsearch-definitive-guide/edit/cn/056_Sorting/90_What_is_relevance.asciidoc">edit</a>
</h2>
</div></div></div>
<p>我们曾经讲过，默认情况下，返回结果是按相关性倒序排列的。
但是什么是相关性？ 相关性如何计算？</p>
<p>每个文档都有相关性评分，用一个正浮点数字段 <code class="literal">_score</code> 来表示 。 <code class="literal">_score</code> 的评分越高，相关性越高。</p>
<p>查询语句会为每个文档生成一个 <code class="literal">_score</code> 字段。评分的计算方式取决于查询类型
不同的查询语句用于不同的目的： <code class="literal">fuzzy</code> 查询会计算与关键词的拼写相似程度，<code class="literal">terms</code> 查询会计算
找到的内容与关键词组成部分匹配的百分比，但是通常我们说的 <em>relevance</em> 是我们用来计算全文本字段的值相对于全文本检索词相似程度的算法。</p>
<p>Elasticsearch 的相似度算法被定义为检索词频率/反向文档频率， <em>TF/IDF</em> ，包括以下内容：</p>
<div class="variablelist">
<dl class="variablelist">
<dt>
<span class="term">
检索词频率
</span>
</dt>
<dd>
检索词在该字段出现的频率？出现频率越高，相关性也越高。 字段中出现过 5 次要比只出现过 1 次的相关性高。
</dd>
<dt>
<span class="term">
反向文档频率
</span>
</dt>
<dd>
每个检索词在索引中出现的频率？频率越高，相关性越低。检索词出现在多数文档中会比出现在少数文档中的权重更低。
</dd>
<dt>
<span class="term">
字段长度准则
</span>
</dt>
<dd>
字段的长度是多少？长度越长，相关性越低。 检索词出现在一个短的 title 要比同样的词出现在一个长的 content 字段权重更大。
</dd>
</dl>
</div>
<p>单个查询可以联合使用 TF/IDF 和其他方式，比如短语查询中检索词的距离或模糊查询里的检索词相似度。</p>
<p>相关性并不只是全文本检索的专利。也适用于 yes|no 的子句，匹配的子句越多，相关性评分越高。</p>
<p>如果多条查询子句被合并为一条复合查询语句，比如 bool 查询，则每个查询子句计算得出的评分会被合并到总的相关性评分中。</p>
<div class="tip admon">
<div class="icon"></div>
<div class="admon_content">
<p>我们有一️整章着眼于相关性计算和如何让其配合你的需求 <a class="xref" href="controlling-relevance.html" title="控制相关度"><em>控制相关度</em></a>。</p>
</div>
</div>
<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="explain"></a>理解评分标准<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elasticsearch-cn/elasticsearch-definitive-guide/edit/cn/056_Sorting/90_What_is_relevance.asciidoc">edit</a>
</h3>
</div></div></div>
<p>当调试一条复杂的查询语句时，想要理解  <code class="literal">_score</code> 究竟是如何计算是比较困难的。Elasticsearch 在
每个查询语句中都有一个 explain 参数，将 <code class="literal">explain</code> 设为 <code class="literal">true</code>  就可以得到更详细的信息。</p>
<div class="pre_wrapper lang-sense">
<pre class="programlisting prettyprint lang-sense">GET /_search?explain <a id="CO29-1"></a><i class="conum" data-value="1"></i>
{
   "query"   : { "match" : { "tweet" : "honeymoon" }}
}</pre>
</div>
<div class="sense_widget" data-snippet="snippets/056_Sorting/90_Explain.json"></div>
<div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO29-1"><i class="conum" data-value="1"></i></a></p>
</td>
<td align="left" valign="top">
<p><code class="literal">explain</code> 参数可以让返回结果添加一个 <code class="literal">_score</code> 评分的得来依据。</p>
</td>
</tr>
</table>
</div>
<div class="note admon">
<div class="icon"></div>
<div class="admon_content">
<p>增加一个 <code class="literal">explain</code> 参数会为每个匹配到的文档产生一大堆额外内容，但是花时间去理解它是很有意义的。 如果现在看不明白也没关系 — 等你需要的时候再来回顾这一节就行。下面我们来一点点的了解这块知识点。</p>
</div>
</div>
<p>首先，我们看一下普通查询返回的元数据：</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">{
    "_index" :      "us",
    "_type" :       "tweet",
    "_id" :         "12",
    "_score" :      0.076713204,
    "_source" :     { ... trimmed ... },</pre>
</div>
<p>这里加入了该文档来自于哪个节点哪个分片上的信息，这对我们是比较有帮助的，因为词频率和 文档频率是在每个分片中计算出来的，而不是每个索引中：</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">    "_shard" :      1,
    "_node" :       "mzIVYCsqSWCG_M_ZffSs9Q",</pre>
</div>
<p>然后它提供了 <code class="literal">_explanation</code> 。每个入口都包含一个 <code class="literal">description</code> 、 <code class="literal">value</code>  、 <code class="literal">details</code> 字段，它分别告诉你计算的类型、计算结果和任何我们需要的计算细节。</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">"_explanation": { <a id="CO30-1"></a><i class="conum" data-value="1"></i>
   "description": "weight(tweet:honeymoon in 0)
                  [PerFieldSimilarity], result of:",
   "value":       0.076713204,
   "details": [
      {
         "description": "fieldWeight in 0, product of:",
         "value":       0.076713204,
         "details": [
            {  <a id="CO30-2"></a><i class="conum" data-value="2"></i>
               "description": "tf(freq=1.0), with freq of:",
               "value":       1,
               "details": [
                  {
                     "description": "termFreq=1.0",
                     "value":       1
                  }
               ]
            },
            { <a id="CO30-3"></a><i class="conum" data-value="3"></i>
               "description": "idf(docFreq=1, maxDocs=1)",
               "value":       0.30685282
            },
            { <a id="CO30-4"></a><i class="conum" data-value="4"></i>
               "description": "fieldNorm(doc=0)",
               "value":        0.25,
            }
         ]
      }
   ]
}</pre>
</div>
<div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO30-1"><i class="conum" data-value="1"></i></a></p>
</td>
<td align="left" valign="top">
<p><code class="literal">honeymoon</code> 相关性评分计算的总结</p>
</td>
</tr>
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO30-2"><i class="conum" data-value="2"></i></a></p>
</td>
<td align="left" valign="top">
<p>检索词频率</p>
</td>
</tr>
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO30-3"><i class="conum" data-value="3"></i></a></p>
</td>
<td align="left" valign="top">
<p>反向文档频率</p>
</td>
</tr>
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO30-4"><i class="conum" data-value="4"></i></a></p>
</td>
<td align="left" valign="top">
<p>字段长度准则</p>
</td>
</tr>
</table>
</div>
<div class="warning admon">
<div class="icon"></div>
<div class="admon_content">
<p>输出 <code class="literal">explain</code> 结果代价是十分昂贵的，它只能用作调试工具 。千万不要用于生产环境。</p>
</div>
</div>
<p>第一部分是关于计算的总结。告诉了我们 <code class="literal">honeymoon</code> 在 <code class="literal">tweet</code> 字段中的检索词频率/反向文档频率或TF/IDF，
（这里的文档 <code class="literal">0</code> 是一个内部的 ID，跟我们没有关系，可以忽略。）</p>
<p>然后它提供了权重是如何计算的细节：</p>
<p>检索词频率:</p>
<pre class="literallayout">检索词 `honeymoon` 在这个文档的 `tweet` 字段中的出现次数。</pre>

<p>反向文档频率:</p>
<pre class="literallayout">检索词 `honeymoon` 在索引上所有文档的 `tweet` 字段中出现的次数。</pre>

<p>字段长度准则:</p>
<pre class="literallayout">在这个文档中， `tweet` 字段内容的长度 -- 内容越长，值越小。</pre>

<p>复杂的查询语句解释也非常复杂，但是包含的内容与上面例子大致相同。
通过这段信息我们可以了解搜索结果是如何产生的。</p>
<div class="tip admon">
<div class="icon"></div>
<div class="admon_content">
<p>JSON 形式的 <code class="literal">explain</code> 描述是难以阅读的，
但是转成 YAML 会好很多，只需要在参数中加上 <code class="literal">format=yaml</code> 。</p>
</div>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="explain-api"></a>理解文档是如何被匹配到的<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elasticsearch-cn/elasticsearch-definitive-guide/edit/cn/056_Sorting/90_What_is_relevance.asciidoc">edit</a>
</h3>
</div></div></div>
<p>当 <code class="literal">explain</code> 选项加到某一文档上时， <code class="literal">explain</code> api 会帮助你理解为何这个文档会被匹配，更重要的是，一个文档为何没有被匹配。
</p>
<p>请求路径为 <code class="literal">/index/type/id/_explain</code> ，如下所示：</p>
<div class="pre_wrapper lang-sense">
<pre class="programlisting prettyprint lang-sense">GET /us/tweet/12/_explain
{
   "query" : {
      "bool" : {
         "filter" : { "term" :  { "user_id" : 2           }},
         "must" :  { "match" : { "tweet" :   "honeymoon" }}
      }
   }
}</pre>
</div>
<div class="sense_widget" data-snippet="snippets/056_Sorting/90_Explain_API.json"></div>
<p>不只是我们之前看到的充分解释 ，我们现在有了一个 <code class="literal">description</code> 元素，它将告诉我们：</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">"failure to match filter: cache(user_id:[2 TO 2])"</pre>
</div>
<p>也就是说我们的 <code class="literal">user_id</code> 过滤子句使该文档不能匹配到。</p>
</div>

</div>
<div class="navfooter">
<span class="prev">
<a href="multi-fields.html">« 字符串排序与多字段</a>
</span>
<span class="next">
<a href="docvalues-intro.html">Doc Values 介绍 »</a>
</span>
</div>
</div>

                  <!-- end body -->
                </div>
                <div class="col-xs-12 col-sm-4 col-md-4" id="right_col">
                  <div id="rtpcontainer" style="display: block;">
                    <div class="mktg-promo">
                      <h3>Most Popular</h3>
                      <ul class="icons">
                        <li class="icon-elasticsearch-white"><a href="https://www.elastic.co/webinars/getting-started-elasticsearch?baymax=default&amp;elektra=docs&amp;storm=top-video">Get Started with Elasticsearch: Video</a></li>
                        <li class="icon-kibana-white"><a href="https://www.elastic.co/webinars/getting-started-kibana?baymax=default&amp;elektra=docs&amp;storm=top-video">Intro to Kibana: Video</a></li>
                        <li class="icon-logstash-white"><a href="https://www.elastic.co/webinars/introduction-elk-stack?baymax=default&amp;elektra=docs&amp;storm=top-video">ELK for Logs &amp; Metrics: Video</a></li>
                      </ul>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </section>

        </div>


<div id="elastic-footer"></div>
<script src="https://www.elastic.co/elastic-footer.js"></script>
<!-- Footer Section end-->

      </section>
    </div>

<script src="/guide/static/jquery.js"></script>
<script type="text/javascript" src="/guide/static/docs.js"></script>
<script type="text/javascript">
  window.initial_state = {}</script>
  </body>
</html>
